//基于select选择的Zepto select职位多选 包装集的插件选择
(function($){
    $.fn.select_position = function(options){
        var opts = $.extend({
            select_title: '',              //select选项值（标题值）
            selectArr:'',                  //隐藏表单id值(数组形式传入多个)
            opt_position: '',              //select职位选项值（数组json对象）
            select_text:'.select_text',    //默认为当前select文本值
            length: '5',                   //默认选择5个
            select_con:"#select_con",      //追加的内容(快捷方式无啥用)
            positionSelect:"#positionSelect",      //追加职位前缀(可忽略快捷方式无啥用)
            callback:function(arrObj){}    //成功确定以后执行的回调函数
        },options||{}); //合并内容
        //直接指向this
        var othis = this;
        var level;
        var pid;
        var jobArray=[];
        var nameArray=[];
        var arrObj=[];

        var set_height;
        var handler;//设置事件禁止开启参数
        var firstScroll;
        var select_con_width;
        ajaxPosition();
        //加载职位
        function ajaxPosition(){
            $.each(opts.selectArr,function(k,v){
                if($(v).val() != '' &&  $(v).val() != '0'){
                    jobArray.push($(v).val());
                }
            });
            if(jobArray.length > 0){
                //获取职位名字
                getPositionName(jobArray);
                function getPositionName(arr){
                    $.post('/common/get_position_name/' + arr.join(","),{ '_token': _token},function (data) {
                        arrObj = data;
                        $.each(data,function(k,v){
                            nameArray.push(v.text);
                        });
                        othis.find(opts.select_text).html(mSubstr(nameArray.join(","),32));
                        //点击职位
                        othis.click(function(){
                            clickPosition(); //点击职位
                        });
                    });
                }
            }else{
                othis.click(function(){
                    clickPosition(); //点击职位
                });
            }
        }
        //点击职位
        function clickPosition() {
            if ($(opts.select_con).length > 0) {
                return false;
            }
            level = 1;
            //加载职位身份
            load_position();

            firstScroll=new IScroll(opts.select_con+" #first",{preventDefault:false });
            //设置事件禁止开启参数
            handler=function (e) { e.preventDefault();};
            document.addEventListener('touchmove', handler, isPassive() ? {
                capture: false,
                passive: false
            } : false);

            //判断存在不存在
            jobArray=[];
            $.each(opts.selectArr, function (k, v) {
                if ($(v).val() != '' && $(v).val() != '0') {
                    jobArray.push($(v).val());
                }
            });
            arrObj=[];
            if (jobArray.length > 0) {
                $.post('/common/get_position_name/' + jobArray.join(","), {'_token': _token}, function (data) {
                    arrObj = data;
                    loadSelect();
                });
            } else {
                loadSelect();
            }
        }
        //加载选项
        function  loadSelect(){
            if(arrObj.length > 0){
                //隐藏表单是不有值
                var str = '';
                var positionSelect = str_trim(opts.positionSelect);
                $.each(arrObj,function(k,v){
                    str+='<span id="'+ positionSelect + v.value +'">'+v.text+'<i data-id="'+v.value+'"></i></span>';
                });
                $(opts.select_con).find('.selected').show().find('dd').append(str);
                setHeight();
                //点击关闭选项
                $(opts.select_con).find('.selected').find('span i').click(function(){
                    var cthis = $(this);
                    $(this).parent('span').remove();
                    setHeight();
                    //删除数组中的值
                    $.each(arrObj,function(k,v){
                        if(v.value == cthis.attr('data-id')){
                            arrObj.splice(k,1);
                        }
                    });
                });
            }else{
                setHeight();
            }
            //关闭加载层 清除select
            $(opts.select_con).find('.close').click(function(){
                if(level == '1'){
                    assignment();
                    //设置事件禁止开启参数
                    document.removeEventListener('touchmove',handler,false);
                }else if(level == '2'){
                    level = 1;
                    if(!$(opts.select_con).find('.select_list').find('ul').hasClass('first')){
                        $(opts.select_con).find('.select_list').find('ul').addClass('first');
                    }
                    //循环职位列表
                    var str = '';
                    if(opts.opt_position.length > 0){
                        $.each(opts.opt_position,function(k,v){
                            str+='<li><a data-id="'+ v.text +'"><span>'+ v.value +'</span></a></li>';
                        });
                    }
                    $(opts.select_con).find('.select_list').find('ul').html(str);
                    setHeight();

                    $(opts.select_con).find('.select_list').find('ul li a').click(function(){
                        level = 2;
                        twoLoadPosition($(this).attr('data-id'));
                    });

                }else if(level == '3'){
                    level = 2;
                    twoLoadPosition(pid);
                    setHeight();
                }
            });
            //确定按钮-------------------------------------------------------------------------------------------------
            $(opts.select_con).find('#determine').click(function(){
                /**清空数组里面的值**/
                for (i=0;i<opts.selectArr.length;i++ ){
                    $(opts.selectArr[i]).val("");
                }
                othis.find(opts.select_text).html('请选择'+opts.select_title);
                nameArray = [];
                if(arrObj.length > 0){
                    $.each(arrObj,function (k,v){
                        $(opts.selectArr[k]).val(v.value);
                        nameArray.push(v.text);
                    });
                    othis.find(opts.select_text).html(mSubstr(nameArray.join(","),32));
                }
                assignment();
                //确定以后执行的回调函数
                opts.callback(arrObj);
                //设置事件禁止开启参数
                document.removeEventListener('touchmove',handler,false);
            });

            //22级加载
            $(opts.select_con).find('.select_list').find('ul li a').click(function(){
                level = 2;
                twoLoadPosition($(this).attr('data-id'));
            });
        }
        //加载二级选项
        function twoLoadPosition(curr_id){
            $.ajax({
                url:'/common/secondposition/'+ curr_id,
                dataType:"json",
                type:"GET",
                success: function(data){
                    //循环二级职位
                    if(data.length > 0){
                        var str = '';
                        $.each(data,function(k,v){
                            str+='<li><a data-id="'+ v.text +'"><span>'+v.value +'</span></a></li>';
                        });
                        $(opts.select_con).find('.select_list').find('ul').html(str);
                        if(!$(opts.select_con).find('.select_list').find('ul').hasClass('first')){
                            $(opts.select_con).find('.select_list').find('ul').addClass('first');
                        }
                        //设置高度
                        setHeight();
                        //33级加载
                        $(opts.select_con).find('.select_list').find('ul li a').click(function(){
                            level = 3;
                            var twothis= $(this);
                            var curr_html = $(this).find('span').html();
                            var curr_cid = $(this).attr('data-id');
                            $.ajax({
                                url:'/common/thirdposition/'+ curr_cid,
                                dataType:"json",
                                type:"GET",
                                success: function(data){
                                    //判断有没有
                                    if(data.length > 0){
                                        //获取上级的ID
                                        pid = curr_id;
                                        var str = '';
                                        //循环三级职位
                                        $.each(data,function(k,v){
                                            str+='<li><a data-id="'+ v.text +'"><span>'+ v.value +'</span></a></li>';
                                        });
                                        $(opts.select_con).find('.select_list ul').removeClass('first').html(str);

                                        if(arrObj.length > 0){
                                            //隐藏表单是不有值
                                            $.each(arrObj,function(k,v){
                                                $(opts.select_con).find('.select_list').find('ul li a').each(function(){
                                                    if($(this).attr('data-id') == v.value){
                                                        $(this).parent('li').addClass('sel');
                                                    }
                                                });
                                            });
                                            //点击关闭选项
                                            $(opts.select_con).find('.selected').find('span i').click(function(){
                                                var cthis = $(this);
                                                $(opts.select_con).find('.select_list').find('ul li a').each(function(){
                                                    if($(this).attr('data-id') == cthis.attr('data-id')){
                                                        $(this).parent('li').removeClass('sel');
                                                    }
                                                });
                                                //设置高度
                                                setHeight();
                                            });
                                        }
                                        //设置高度
                                        setHeight();
                                        //点击当前列表
                                        $(opts.select_con).find('.select_list ul').find('li a').click(function(){
                                            setSelect($(this));
                                            setHeight();
                                        });
                                    }
                                },
                                error:function(){
                                    layerMsg('可能网络原因引起的错误！',1);
                                }
                            });
                        });
                    }
                },
                error:function(){
                    layerMsg('可能网络原因引起的错误！',1);
                }
            });
        }
        //添加已选内容
        function  setSelect(selthis){
            //获取当前的地区和cid
            var curr_area = selthis.find('span').html();
            var curr_cid = selthis.attr('data-id');
            if(selthis.parent('li').hasClass('sel')){
                selthis.parent('li').removeClass('sel');
                $(opts.select_con).find('.selected').find('dd').find(opts.positionSelect+curr_cid).remove();
                //删除数组中的值
                $.each(arrObj,function(k,v){
                    if(v.value == curr_cid){
                        arrObj.splice(k,1);
                    }
                });
            }else{
                //只能选择5个
                if($(opts.select_con).find('.selected').find('span').size() >= opts.length){
                    layerMsg('最多只能选择'+opts.length+'个',1);
                    return false;
                }
                selthis.parent('li').addClass('sel');
                var positionSelect = str_trim(opts.positionSelect);

                var str = '';

                str+='<span id="'+positionSelect +curr_cid+'">'+curr_area+'<i data-id="'+curr_cid+'"></i></span>';
                $(opts.select_con).find('.selected').find('dd').append(str);
                //添加到数组
                arrObj.push({'text':curr_area,'value':curr_cid});
                //console.log(arrObj);
            }
            //点击关闭按钮 删除选项
            $(opts.select_con).find('.selected').find(opts.positionSelect+curr_cid).find('i').click(function(){
                var cthis = $(this);
                $(this).parent('span').remove();
                if(selthis.attr('data-id') == cthis.attr('data-id')){
                    selthis.parent('li').removeClass('sel');
                }
                //删除数组中的值
                $.each(arrObj,function(k,v){
                    if(v.value == cthis.attr('data-id')){
                        arrObj.splice(k,1);
                    }
                });
                setHeight();
            });
        }
        //设置高度
        function setHeight(){
            //有没有添加选项设置高度
            if($(opts.select_con).find('.selected').find('span').size() > 0){
                $(opts.select_con).find('.selected').show();
                var selectedHeight = $(opts.select_con).find('.selected').height();
                //设置最大高度
                set_height = $(opts.select_con).height() - $(opts.select_con).find('.select_header').height() - selectedHeight;
                $(opts.select_con).find('.select_list').css({
                    'height':set_height + 'px'
                });
                firstScroll.refresh();
            }else{
                $(opts.select_con).find('.selected').hide();
                set_height = $(opts.select_con).height() - $(opts.select_con).find('.select_header').height() ;
                $(opts.select_con).find('.select_list').css({
                    'height':set_height + 'px'
                });
                firstScroll.refresh();
            }
        }
        //设置监听滚动
        function isPassive() {
            var supportsPassiveOption = false;
            try {
                addEventListener("test", null, Object.defineProperty({}, 'passive', {
                    get: function () {
                        supportsPassiveOption = true;
                    }
                }));
            } catch(e) {}
            return supportsPassiveOption;
        }
        //加载内容
        function load_position(){
            var select_con = str_trim(opts.select_con);
            var str = '';
            if($('.masking').length <= 0){
                str+='<div class="masking" id="masking"></div>';
            }
            str+='<div class="select_con" id="'+select_con+'">';
            str+='<div class="select_header">';
            str+='<a class="close"></a>';
            str+='<div class="title">'+opts.select_title+'</div>';
            str+='<a id="determine" class="determine">确定</a>';
            str+='</div>';

            str+='<div class="select_list">';
            str+='<div class="selected">';
            str+='<dl>';
            str+='<dt>已选：</dt>';
            str+='<dd>';
            str+='</dd>';
            str+='</dl>';
            str+='</div>';

            str+='<div id="first">';
            str+='<ul class="first">';
            //循环职位列表
            if(opts.opt_position.length > 0){
                $.each(opts.opt_position,function(k,v){
                    str+='<li><a data-id="'+ v.text +'"><span>'+ v.value +'</span></a></li>';
                });
            }
            str+='</ul>';
            str+='</div>';

            str+='</div>';
            str+='</div>';
            //追击添加的内容
            $('body').append(str);
            $(opts.select_con).find('.select_list').show();

            $(".masking").show();
            //当文档的宽度大于内容的宽度时
            if($(document).width() > $(opts.select_con).width()){
                select_con_width = ( $(document).width() -  $(opts.select_con).width() )/2 ;
                $(opts.select_con).animate({
                    left:select_con_width + 'px',
                    'animation':'select_start 0.4s 0s ease',
                    'display':'block'
                }, 300);
            }else{
                $(opts.select_con).animate({
                    left:'0',
                    'animation':'select_start 0.4s 0s ease',
                    'display':'block'
                }, 300);
            }
        }
        //赋值内容
        function assignment(){
            $(opts.select_con).animate({
                'left':'7.5rem',
                'animation':'select_end .4s 0s ease',
                'display':'block'
            }, 300 ,function(){
                $(opts.select_con).remove();
                $(".masking").hide();
            });
        }
        return this;
    };
})(Zepto);

